import { baseURL } from "./config";
import Toast from '../components/vant/toast/toast';
import { getToken } from './login'
const http = ({url, data, method, isNeedLogin}) => {
    return new Promise((resolve, reject) => {
        getToken(false).then(token => {
            wx.request({
                url: baseURL + url,
                data: data,
                method: method,
                dataType:'json',
                header: {
                    token: token
                },
                success: (res) => {
                    switch(res.data.code) {
                        case 0:
                            resolve(res)
                            break;
                            // wx.redirectTo({ url: `/pages/authorization/authorization` })
                            // break;
                        case 10025:
                            reject(res)
                            break;
                        case 10043:
                        case 10042:
                        case 10024:
                            wx.removeStorageSync('wxToken')
			                wx.removeStorageSync('wxUserDetails')
                            wx.redirectTo({ url: `/pages/authorization/authorization` })
                            // getToken().then(() => {
                            //     resolve({ data: { code: 100 } })
                            // })
                            break;
                        case 1000:
                        // case 2000:
                            Toast.fail(res.data.message);
                            wx.navigateTo({ url: '/pages/myContent/myContent' })
                            break;
                        default:
                            Toast.fail(res.data.message)
                            reject(res)
                    }
                }
            })
        })
    })
}

const _get = (url, data = {}, isNeedLogin = true) => {
    return http({
        url,
        data,
        isNeedLogin
    })
}
const _post = (url, data = {}, isNeedLogin = true) => {
    return http({
        url,
        data,
        method: 'POST',
        isNeedLogin
    })
}
const _delete = (url, data = {}, isNeedLogin = true) => {
    return http({
        url,
        data,
        method: 'DELETE',
        isNeedLogin
    })
}
const _patch = (url, data = {}, isNeedLogin = true) => {
    return http({
        url,
        data,
        method: 'PATCH',
        isNeedLogin
    })
}
const _put = (url, data = {}, isNeedLogin = true) => {
    return http({
        url,
        data,
        method: 'PUT',
        isNeedLogin
    })
}
module.exports = {
    baseURL,
    _get,
    _post,
    _delete,
    _patch,
    _put
}
